import {
  Text,
  View,
  ScrollView,
  Image,
  TouchableOpacity,
  StyleSheet,
  TextInput,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import React, { useEffect, useState } from "react";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter,useLocalSearchParams } from "expo-router"; // 引入 useRouter
import QRCode from "react-native-qrcode-svg";
import { copyToClipboard } from "@/uitls/common";
import SelectionModal from "@/components/SelectionModal";
import { useTranslation } from "react-i18next";

import {
  findAllSimpleAssetsFnApi,
  findAssetChainNetInfoFnAPi,
  getAssetCoinDepositAddressFnApi,
  withdrawAssetSave
} from "./api";
import { ToastAPI } from "@/components/Toast";
import useInputWithDone from "@/hooks/useInputWithDone";
export default function Recharge() {
  const { t } = useTranslation();

  const [currencyModalVisible, setCurrencyModalVisible] = useState(false);
  const [networkModalVisible, setNetworkModalVisible] = useState(false);
  const [addressModalVisible, setAddressModalVisible] = useState(false);
  const router = useRouter(); // 获取路由对象
  const [currencyList, setCurrencyList] = useState([]);
  const [currencyItemInfo, setCurrencyItemInfo] = useState<any>(null);
  const [networkList, setNetworkList] = useState([]);
  const [networkItemInfo, setNetworkItemInfo] = useState<any>(null);
  const [addressListInfo, setAddressListInfo] = useState<any>(null);
  const [qrCode, setQrCode] = useState("");
  const getCurrencyList = async () => {
    const res: any = await findAllSimpleAssetsFnApi();
    setCurrencyList(res.result);
  };
  const params = useLocalSearchParams<{ 
    assetId: string,symbol:string
    }>();
    const initData = async (item:any) => {
      setCurrencyItemInfo(item);
          setCurrencyModalVisible(false);
          setNetworkItemInfo(null);
          ToastAPI.loading("加载中...");
          setQrCode("");
          //调用接口请求网卡
          try {
            const res: any = await findAssetChainNetInfoFnAPi({
              assetId: item.id,
            });
            ToastAPI.close();
            if (res.code === 0) {
              setNetworkList(res.result);
            } else {
              ToastAPI.error(res?.errMsg || "网卡获取失败");
            }
          } catch (error) {
            ToastAPI.close();
            // 捕获错误并关闭加载提示
            ToastAPI.error(JSON.stringify(error) || "请求发生错误，请稍后重试");
          }
    };
  useEffect(() => {
    getCurrencyList();
    if(params?.assetId){
      initData({id:params?.assetId,symbol:params?.symbol})
    }
  }, []);
  const [
    withdrawalQuantity,
    setWithdrawalQuantity,
    handleWithdrawalQuantityDone,
  ] = useInputWithDone() as any;
  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <Image
              source={require("@/assets/images/return-left.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <Text className="text-[#fff] text-[18px]">
              {t("WithdrawalCurrency.withdrawal")}
            </Text>
          </View>
          <TouchableOpacity
            onPress={() => router.push("/recharge/withdrawalHistorical")}
          >
            <Image
              source={require("@/assets/images/jl.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
        </View>
        <ScrollView
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          style={{ flex: 1 }}
        >
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("WithdrawalCurrency.currency")}
            </Text>
            <TouchableOpacity onPress={() => setCurrencyModalVisible(true)}>
              <View
                style={styles.input}
                className="flex-row justify-between gap-[10px]"
              >
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: !currencyItemInfo ? "#949494" : "#fff" }}
                >
                  {!currencyItemInfo
                    ? t("WithdrawalCurrency.select_currency")
                    : currencyItemInfo.symbol}
                </Text>
                <Text className="text-[rgb(83,192,255)] text-[14px] leading-[50px]">
                  {t("WithdrawalCurrency.switch_currency")}
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("WithdrawalCurrency.network")}
            </Text>
            <TouchableOpacity
              onPress={() => {
                setNetworkModalVisible(true);
              }}
            >
              <View style={styles.input} className="flex-row justify-between">
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: !networkItemInfo ? "#949494" : "#fff" }}
                >
                  {!networkItemInfo
                    ? t("WithdrawalCurrency.select_network")
                    : networkItemInfo.chainFullName}
                </Text>
                <Text className="text-[rgb(83,192,255)] text-[14px] leading-[50px]">
                  {t("WithdrawalCurrency.switch_network")}
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("WithdrawalCurrency.withdrawal_address")}
            </Text>
            <TouchableOpacity
              onPress={() => {
                setAddressModalVisible(true);
              }}
            >
              <View style={styles.input} className="flex-row justify-between">
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: !addressListInfo ? "#949494" : "#fff" }}
                >
                  {!addressListInfo
                    ? t("WithdrawalCurrency.select_withdrawal_address")
                    : addressListInfo.name}
                </Text>
                <Text className="text-[rgb(83,192,255)] text-[14px] leading-[50px]">
                  {t("WithdrawalCurrency.switch_withdrawal_address")}
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("WithdrawalCurrency.quantity")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handleWithdrawalQuantityDone}
              blurOnSubmit={true}
              keyboardType="numeric"
              placeholder={t("WithdrawalCurrency.input_withdrawal_quantity")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={withdrawalQuantity}
              onChangeText={setWithdrawalQuantity}
            />
          </View>
          {/* <View className="mt-[10px]">
            <Text className="text-[#fff] text-[14px]">
              {t("WithdrawalCurrency.available_balance")}：0.00000USDT
            </Text>
          </View> */}
          <View className="mt-[22px]">
            <Text className="text-[#D7D7D7] text-[16px]">
              {t("WithdrawalCurrency.fee")}
            </Text>
            <TouchableOpacity>
              <View style={styles.input} className="flex-row justify-between">
                <Text
                  className="flex-1 text-[14px] leading-[50px]"
                  style={{ color: "#fff" }}
                >
                  0.0000
                </Text>
              </View>
            </TouchableOpacity>
          </View>
          <TouchableOpacity onPress={async() => {
              ToastAPI.loading("加载中...");
            try {
              const res: any = await withdrawAssetSave({
                assetId: currencyItemInfo.id,
              coinId: networkItemInfo.coinId, 
              withdrawAmount: withdrawalQuantity,
              withdrawToAddress: qrCode,
              });
              ToastAPI.close();
              if (res.code === 0) {
                ToastAPI.success("提币成功");
                router.back()
              } else {
                ToastAPI.error(res?.errMsg || "提币失败");
              }
            } catch (error) {
              ToastAPI.close();
              // 捕获错误并关闭加载提示
              ToastAPI.error(JSON.stringify(error) || "请求发生错误，请稍后重试");
            }
          }}>
            <LinearGradient
              style={styles.loginBtn}
              colors={["#3D7FFF", "#6FC2FA"]}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <Text className="text-[#fff] text-[16px]">
                {t("WithdrawalCurrency.confirm_withdrawal")}
              </Text>
            </LinearGradient>
          </TouchableOpacity>
        </ScrollView>
      </View>
      <SelectionModal
        visible={currencyModalVisible}
        title="选择币种"
        listData={currencyList}
        renderKey="name"
        onClose={() => setCurrencyModalVisible(false)}
        onSelect={async (item) => {
          initData(item)
        }}
        renderItem={(item) => (
          <View className="flex-1 flex-row gap-[10px] justify-between items-center">
            <View className="flex-row gap-[10px] items-center flex-1">
              <Image
                source={{ uri: item.logo }}
                className="w-[20px] h-[20px] rounded-full"
              />
              <Text className="text-[16px] text-[#fff]">{item.symbol}</Text>
              <Text className="text-[16px] text-[#949494]">
                {item.fullName}
              </Text>
            </View>
            {item.depositStatus === 1 && (
              <Text className="text-[red] text-[14px]">暂停</Text>
            )}
          </View>
        )}
      />
      <SelectionModal
        visible={networkModalVisible}
        title="选择主网"
        listData={networkList}
        renderKey="name"
        onClose={() => setNetworkModalVisible(false)}
        onSelect={async (item) => {
          setQrCode("");
          setNetworkItemInfo(item);
          setNetworkModalVisible(false);
          ToastAPI.loading("加载中...");
          //调用接口请求网卡
          setTimeout(async () => {
            try {
              const res: any = await getAssetCoinDepositAddressFnApi({
                coinId: item.coinId,
              });
              ToastAPI.close();
              if (res.code === 0) {
                setQrCode(res.result);
              } else {
                ToastAPI.error(res?.errMsg || "充值地址获取失败");
              }
            } catch (error) {
              ToastAPI.close();
              // 捕获错误并关闭加载提示
              ToastAPI.error(
                JSON.stringify(error) || "请求发生错误，请稍后重试"
              );
            }
          }, 1000);
        }}
        renderItem={(item) => (
          <View className="flex-1">
            <View className="flex-row justify-between gap-[10px] items-center">
              <Text className="text-[#fff] text-[16px]">{item.coinSymbol}</Text>
              <Text className="text-[#fff] text-[16px]">==1分钟</Text>
            </View>
            <View className="flex-row justify-between gap-[10px] items-center">
              <Text className="text-[#949494] text-[14px]">
                {item.chainFullName}
              </Text>
              <Text className="text-[#949494] text-[14px]">15次确认/秒</Text>
            </View>
          </View>
        )}
      />
      <SelectionModal
        visible={addressModalVisible}
        title="选择提币地址"
        listData={qrCode?[
          { name: qrCode },
        ]:[]}
        renderKey="name"
        onClose={() => setAddressModalVisible(false)}
        onSelect={async (item) => {
          setAddressListInfo(item);
          setAddressModalVisible(false);
        }}
        renderItem={(item) => <View className="flex-1">
          <View className="flex-row justify-between gap-[10px] items-center">
            <Text className="text-[#fff] text-[16px]">地址：{item.name}</Text>
          </View>
        </View>}
      />
    </PageContainer>
  );
}

const styles = StyleSheet.create({
  input: {
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
    height: 50,
    paddingHorizontal: 12,
  },
  loginBtn: {
    height: 50,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
  },
  bbtn: {
    height: 50,
    borderRadius: 30,
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
  },
  roundedBorderView: {
    borderWidth: 1,
    borderColor: "#979797",
    borderRadius: 10,
    padding: 25,
    marginTop: 22,
    flexDirection: "column",
    gap: 10,
  },
});
